package view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import org.bushe.swing.event.EventBus;

import constants.Events;

@SuppressWarnings("serial")
public class Battle extends JDialog {

    JFrame parent;
    String res;
    JDialog d;
    JDialog dd;
    JTextField tf;
    JLabel question;

    public Battle(final JFrame p){
        parent = p;
        tf = new JTextField();
    }

    /**
     *
     * @param question battle question
     */
    public final void waitForAnswer(final String question) {
        final JOptionPane p = new JOptionPane();
        final JComponent[] options = {new JButton("OK"), tf};
        ((JButton) options[0]).addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent arg0) {
                //JTextField t = (JTextField) options[1];
                res = tf.getText();
                System.out.println(p.getValue().toString());
                System.out.println(res);
                EventBus.publish(Events.BATTLE_ANS.toString(), res);
                dd.dispose();
                d.dispose();

            }

        });

        p.setOptions(options);
        //p.setOptionType(JOptionPane.DEFAULT_OPTION);
        //p.setWantsInput(true);
        p.setMessage(question);

        d = p.createDialog("Battle");

        dd = new JDialog(JOptionPane.getRootFrame(), d.getTitle());
        this.question = new JLabel(question);
        dd.setLayout(null);
        dd.setBounds(d.getBounds());

        dd.add(this.question);
        dd.add(tf);
        dd.add(options[0]);

        this.question.setBounds(0, 5, dd.getWidth(), 15);
        tf.setBounds(0, 20, dd.getWidth(), 20);
        options[0].setBounds(50, 50, 50, 25);


        dd.setVisible(true);

        //return JOptionPane.showInputDialog(null, question);
    }

    public final void hide(){
//        for(int i = 0; i < JOptionPane.getRootFrame().getComponentCount(); i++)
//            System.out.println(JOptionPane.getRootFrame().getComponent(i));
//        JOptionPane.getRootFrame().dispose();
//
//        new Thread() {
//            public void run() {
//                for (int i = 0; i < 3; i++) {
//                    try {
//                        Thread.sleep(2000);
//                    } catch (InterruptedException e) {
//                    }
//                    JOptionPane.getRootFrame().dispose();
//                }
//            }
//        };
//        d.dispose();
//        this.dispose();
        dd.dispose();
    }
}
